class CampaignObserver < ActiveRecord::Observer
  
  def after_create(campaign)
    update_default(campaign)    
  end
  
  def after_update(campaign)
    update_default(campaign)
    update_user_campaigns(campaign)
  end
  
  def after_destroy(campaign)
    UserCampaign.destroy_all("campaign_id=#{campaign.id}")
  end
  
  private
  def update_user_campaigns(campaign)
    if campaign.ended && !campaign.winner_id
      max_points = UserCampaign.maximum(:points, :conditions=>["is_active=:active and campaign_id=:campaign_id",{:active=>true, :campaign_id=>campaign}])
      uc = UserCampaign.find(:all,:order=>"created_at ASC", :conditions=>["points>=:max_points and is_active=:active and campaign_id=:campaign_id and points>=:minimum_points",{:minimum_points=>campaign.minimum_points,:max_points=>max_points, :active=>true, :campaign_id=>campaign}])
      winner_id = -1     
      if uc.size > 0
        winner_id = uc[0].user_id  
      end
      
      campaign.winner_key = StringUtils::generate_random_words(13)
      campaign.winner_id=winner_id
      campaign.save!
      UserCampaign.update_all("is_active=false", "campaign_id=#{campaign.id}")
    end
  end
  
  def update_default(campaign)
    if campaign.is_default
      #find the other that is home
      old_defaults = Campaign.find_all_by_is_default(true)
      for old_default in old_defaults
        if campaign.id != old_default.id 
          old_default.is_default =false
          old_default.save
        end
      end
    end
    
  end
end
